package com.OnTimeTeam.OnTime;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class NotificationService extends Service{

	NotificationManager nm;
	static final int uniqueID = 1394485;
	
	private static String path;
	
	public int onStartCommand(Intent intent, int flags, int startId) {
		super.onStartCommand(intent, flags, startId);

		path = getApplicationContext().getFilesDir().getPath().toString() + "/reminders.xml";
		
		//Check if there is any alarm on
		ArrayList<AlarmFeatures> alarmsArray = RemindersIO.getAllAlarms(path);
		Boolean isAlarmOn = false;
		ArrayList<AlarmFeatures>  alarmsOn = new ArrayList<AlarmFeatures>();
		for(int i = 0; i < alarmsArray.size(); ++i) {
			if(alarmsArray.get(i).getStatus().equals("On")) {
				isAlarmOn = true;
				alarmsOn.add(alarmsArray.get(i));
			}
		}
		
		
		
		nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
		
		if(isAlarmOn) {
			  
			Intent i = new Intent(NotificationService.this, MainActivity.class);
			PendingIntent pi = PendingIntent.getActivity(NotificationService.this, 0, i, 0);
			String body = getClosestAlarmString(alarmsOn, path);
			String title = "OnTime Smart Alarm Clock";
			  
			Notification n = new Notification(R.drawable.ic_stat_ic_stat_alarm_icon_notification, body, System.currentTimeMillis());
			   
			n.setLatestEventInfo(NotificationService.this, title, body, pi);
			//n.defaults = Notification.FLAG_NO_CLEAR;
			n.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
			
			nm.notify(uniqueID, n);
		}
		else
			nm.cancel(uniqueID);
			
		
		return Service.START_NOT_STICKY;
	}
	
	public static String getClosestAlarmString(ArrayList<AlarmFeatures> alarmsOn, String path) {
		
		Calendar closestAlarmCal = getClosestCalendar(alarmsOn.get(0), path);
		
		for(int i = 1; i < alarmsOn.size(); ++i) {
			Calendar newAlarmCal = getClosestCalendar(alarmsOn.get(i), path);
			if(newAlarmCal.before(closestAlarmCal))
				closestAlarmCal = newAlarmCal;
		}
		
		String answer = "Next alarm set for ";
		
		if((Calendar.getInstance().get(Calendar.DAY_OF_YEAR) == closestAlarmCal.get(Calendar.DAY_OF_YEAR)))
			answer += "Today, ";
		else {
			switch(closestAlarmCal.get(Calendar.DAY_OF_WEEK)){
				case Calendar.SUNDAY:
					answer += "Sun, ";
					break;
				case Calendar.MONDAY:
					answer += "Mon, ";
					break;
				case Calendar.TUESDAY:
					answer += "Tue, ";
					break;
				case Calendar.WEDNESDAY:
					answer += "Wed, ";
					break;
				case Calendar.THURSDAY:
					answer += "Thu, ";
					break;
				case Calendar.FRIDAY:
					answer += "Fri, ";
					break;
				case Calendar.SATURDAY:
					answer += "Sat, ";
					break;
			}
		}
		
		String hour = Integer.toString(closestAlarmCal.get(Calendar.HOUR_OF_DAY));
		String minute = Integer.toString(closestAlarmCal.get(Calendar.MINUTE));
		
		if(closestAlarmCal.get(Calendar.HOUR_OF_DAY) < 10)
			hour = "0" + Integer.toString(closestAlarmCal.get(Calendar.HOUR_OF_DAY));
		if(closestAlarmCal.get(Calendar.MINUTE) < 10)
			minute = "0" + Integer.toString(closestAlarmCal.get(Calendar.MINUTE));
		
		answer += hour + ":" + minute;
		
		return answer;
	}
	
	
	private static Calendar getClosestCalendar(AlarmFeatures af, String path){
		 
		Calendar nextAlarm = null;
		String[] alarmDays = af.getDaysToRepeat().split(", ");
		String[] snoozeFeatures = RemindersIO.getSnoozeAlarmSign(af.getID(), path).split(",");
		if(snoozeFeatures.length == 2){
			
			nextAlarm = Calendar.getInstance();
		    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.getDefault());
		    
		    try {nextAlarm.setTime(sdf.parse(snoozeFeatures[1]));}
		    catch (ParseException e) {e.printStackTrace();}
		}

		//turn on the alarm again 
		for(int i = 0; i < alarmDays.length; ++i) {

			//Create Calendar and set the time in it
			Calendar alarmCal = Calendar.getInstance();//get Calendar object
			alarmCal.set(Calendar.HOUR_OF_DAY, Integer.valueOf(af.getHour()));//set user selection
			alarmCal.set(Calendar.MINUTE, Integer.valueOf(af.getMinute()));//set user selection
			alarmCal.set(Calendar.SECOND, 0);//zero the seconds			
			alarmCal = AlarmSetter.editCalendarDayNotification(AlarmSetter.getDayAsInt(alarmDays[i]), alarmCal);
			
			//set next closest alarm
			if(nextAlarm == null)
				nextAlarm = alarmCal;
			else if(nextAlarm.after(alarmCal)){
				nextAlarm = alarmCal;
			}

		}//end of loop
		

		return nextAlarm;
	}
	
	
	/*public static Calendar getSnoozeCalendar(int alarmID){
		
		String[] snoozeFeatures = RemindersIO.getSnoozeAlarmSign(alarmID, path + "/reminders.xml").split(":");
		
	}*/

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}


}